package com.cedarhd.brzx.common;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cedarhd.brzx.common.constants.RespStatusConstant;
import com.cedarhd.brzx.common.enums.ResultCode;
import lombok.Data;
import org.hibernate.annotations.common.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Evan
 * @date 17/10/30
 */
@Data
public class JsonResult<T> {

    private static Logger log = LoggerFactory.getLogger(JsonResult.class);

    public String resultCode;
    public String msg;
    public Long size = 1L;
    public T result;

    public static JsonResult renderMsg(ResultCode code, Object data) {
        return renderMsg(code.getCode(),code.getMsg(),data);
    }

    public static JsonResult renderMsg(String resultCode,String msg ,Object data){
        JsonResult result = new JsonResult();

        result.resultCode = resultCode;
        result.msg = msg;
        result.result = data;

        return result;
    }

    public static JsonResult renderMsg(ResultCode code) {
        return renderMsg(code,null);
    }

    public static JsonResult renderMsg(Object data) {
        return renderMsg(ResultCode.SUCC,data);
    }



    public static JsonResult getFromResponse(String jsonStr) {


        return  getFromResponse(jsonStr, null);
    }

    public static JsonResult getFromResponse(String jsonStr , String ObjName ) {
        JSONObject response = JSON.parseObject(jsonStr);
        JsonResult resp;
        String resultStatus = response.getString("status");

        log.info("getFromResponse response = {}", response );
        if(resultStatus.equals(RespStatusConstant.OK)){
            String resultJson = response.getString("signedValue");

            JSONObject resultData = JSON.parseObject(resultJson);

            if(StringHelper.isNotEmpty(ObjName)){
                resultData  = resultData.getJSONObject(ObjName);
            }

            resp = JsonResult.renderMsg(resultData);
        } else if(resultStatus.equals(RespStatusConstant.ERROR)){
            String errorCode = response.getString("errorCode");
            String errorMsg = response.getString("message");
            log.error("errorCode ={}, errorMsg={}", errorCode, errorMsg);
            resp =  JsonResult.renderMsg(errorCode, errorMsg, null);
        }else{
            resp =  JsonResult.renderMsg(ResultCode.PARAM_ERROR.getCode(), "数据错误", null);
            log.error("数据转换异常");
        }

        log.info("getFromResponse resp = {}", resp );

        return resp;
    }

}
